"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from celery.result import AsyncResult
from celery.signals import task_prerun, task_postrun, task_failure
from django.utils import timezone
from django.db import transaction
from .models import SistemaPeto


@task_prerun.connect
def peto_prerun(task_id, *args, **kwargs):
    res = AsyncResult(task_id)

    with transaction.atomic():
        SistemaPeto.objects.select_for_update(of=('self',)).filter(tasko_id=task_id).update(
            statuso=res.state,
            komenca_dato=timezone.now()
        )


@task_postrun.connect
def peto_postrun(task_id, retval, state, *args, **kwargs):
    if not isinstance(retval, Exception):
        with transaction.atomic():
            SistemaPeto.objects.select_for_update(of=('self',)).filter(tasko_id=task_id).update(
                statuso=state,
                rezulto=retval,
                fina_dato=timezone.now()
            )


@task_failure.connect
def peto_failure(task_id, exception, einfo, *args, **kwargs):
    res = AsyncResult(task_id)

    with transaction.atomic():
        SistemaPeto.objects.select_for_update(of=('self',)).filter(tasko_id=task_id).update(
            statuso=res.state,
            rezulto={
                'error': str(exception),
                'einfo': str(einfo)
            },
            fina_dato=timezone.now()
        )
